<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./css/bootstrap.min.css" />
    <script src="./js/jquery-3.6.0.min.js"></script>
    <script src="./js/bootstrap.bundle.min.js"></script>
    <style>
      th {
        text-align: center;
      }
      .btn-group {
        display: flex;
        justify-content: space-between;
      }
      .btn-group .btn {
        flex: 1;
        margin: 0 2px;
      }
    </style>
  </head>
  <body>
    <div class="container my-5">
      <h1 class="text-center">miaomiao图书管理系统</h1>

      <!-- Show Add Form Button -->
      <button class="btn btn-success my-3" id="showAddForm">添加图书</button>

      <div class="card">
        <div class="card-header">图书列表</div>
        <div class="card-body">
          <table class="table table-bordered">
            <thead>
              <tr>
                <th>书号</th>
                <th>书名</th>
                <th>作者</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody id="bookList">
              <!-- Book rows will be dynamically inserted here -->
            </tbody>
          </table>
        </div>
      </div>

      <!-- Add Book Modal -->
      <div
        class="modal fade"
        id="addBookModal"
        tabindex="-1"
        aria-labelledby="addBookModalLabel"
        aria-hidden="true"
      >
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="addBookModalLabel">添加图书</h5>
              <button
                type="button"
                class="btn-close"
                data-bs-dismiss="modal"
                aria-label="Close"
              ></button>
            </div>
            <div class="modal-body">
              <form id="bookForm">
                <div class="mb-3">
                  <label for="number" class="form-label">书号</label>
                  <input
                    type="text"
                    class="form-control"
                    id="number"
                    required
                  />
                </div>
                <div class="mb-3">
                  <label for="name" class="form-label">书名</label>
                  <input type="text" class="form-control" id="name" required />
                </div>
                <div class="mb-3">
                  <label for="author" class="form-label">作者</label>
                  <input
                    type="text"
                    class="form-control"
                    id="author"
                    required
                  />
                </div>
                <button type="submit" class="btn btn-primary" id="addBook">
                  添加
                </button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- JavaScript -->
    <script>
      let currentIndex = null;

      const showAddFormButton = $("#showAddForm");
      const addBookModal = new bootstrap.Modal(
        document.getElementById("addBookModal")
      );
      const modalTitle = $("#addBookModalLabel");
      const numberInput = $("#number");

      // Show Add Form Modal
      showAddFormButton.on("click", () => {
        modalTitle.text("添加图书");
        numberInput.prop("disabled", false); // Enable the number input field
        $("#bookForm")[0].reset(); // Clear the form fields
        addBookModal.show();
      });

      // Add Book
      $("#bookForm").on("submit", function (event) {
        event.preventDefault();
        const number = $("#number").val();
        const name = $("#name").val();
        const author = $("#author").val();

        const bookData = { number, name, author };

        if (currentIndex === null) {
          $.ajax({
            url: `http://115.120.245.212:8080/webexam/add_book`,
            method: "GET",
            data:bookData,
            success: function (response) {
              renderBooks();
              addBookModal.hide(); // Hide modal after submission
            },
            error: function (error) {
              console.error("Error adding book:", error);
            },
          });
        } else {
          // Update existing book
          $.ajax({
            url: `http://115.120.245.212:8080/webexam/update_book`,
            method: "GET",
            data:bookData,
            success: function (response) {
              currentIndex = null;
              renderBooks();
              addBookModal.hide(); // Hide modal after submission
            },
            error: function (error) {
              console.error("Error updating book:", error);
            },
          });
        }

        this.reset();
      });

      // Render Book List
      function renderBooks() {
        $.ajax({
          url: "http://115.120.245.212:8080/webexam/list_book",
          method: "GET",
          success: function (data) {
            console.log("data: ", data);
            const bookList = $("#bookList");
            bookList.empty();
            data.forEach((book, index) => {
              console.log(typeof book.number);
              const row = $(`
                <tr>
                  <td>${book.number}</td>
                  <td>${book.name}</td>
                  <td>${book.author}</td>
                  <td>
                    <div class="btn-group" id='btn-group_${book.number}'>
                      <button class="btn btn-info btn-sm" onclick="viewBook('${book.number}')">查看</button>
                      <button class="btn btn-warning btn-sm" onclick="editBook(${index}, '${book.number}')">编辑</button>
                      <button class="btn btn-danger btn-sm" onclick="deleteBook('${book.number}')">删除</button>
                    </div>
                  </td>
                </tr>
              `);
              bookList.append(row);
            });
          },
          error: function (error) {
            console.error("Error fetching books:", error);
          },
        });
      }

      // View Book
      function viewBook(number) {
        $.ajax({
          url: `http://115.120.245.212:8080/webexam/get_book?number=${number}`,
          method: "GET",
          success: function (book) {
            alert(`书名: ${book.name}\n作者: ${book.author}`);
          },
          error: function (error) {
            console.error("Error viewing book:", error);
          },
        });
      }

      // Edit Book
      function editBook(index, number) {
        const numberStr = number.toString();
        $.ajax({
          url: `http://115.120.245.212:8080/webexam/get_book?number=${numberStr}`,
          method: "GET",
          success: function (book) {
            $("#number").val(book.number);
            $("#name").val(book.name);
            $("#author").val(book.author);
            currentIndex = index;
            modalTitle.text("编辑图书");
            numberInput.prop("disabled", true); // Disable the number input field
            addBookModal.show();
          },
          error: function (error) {
            console.error("Error fetching book for edit:", error);
          },
        });
      }

      // Delete Book
      function deleteBook(number) {
        console.log("deleteBook:", number);
        console.log(typeof number);
        if (confirm("确定要删除这本书吗？")) {
          $.ajax({
            url: `http://115.120.245.212:8080/webexam/delete_book?number=${number}`,
            method: "GET",
            success: function (response) {
              renderBooks();
            },
            error: function (error) {
              console.error("Error deleting book:", error);
            },
          });
        }
      }

      // Fetch books on page load
      $(document).ready(function () {
        renderBooks();
      });
    </script>
  </body>
</html>

